package com.jackeysun.app_widget

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.jackeysun.app_widget.databinding.ActivityMain2Binding
import com.jackeysun.widget.calendar.*
import com.jackeysun.widget.calendar.interf.OnSelectDateListener
import com.jackeysun.widget.calendar.view.Calendar
import com.jackeysun.widget.calendar.view.MonthPager
import java.util.*

class MainActivity2 : AppCompatActivity() {

    private lateinit var mainBinding: ActivityMain2Binding

    private lateinit var calendarAdapter: CalendarViewAdapter
    private var mCurrentPage = MonthPager.CURRENT_DAY_INDEX
    private var currentCalendars: ArrayList<Calendar> = ArrayList<Calendar>()
    private var initiated = false

    private val onSelectDateListener =
        object : OnSelectDateListener {
            override fun onSelectDate(date: CalendarDate?) {
                refreshMonthPager(date?:return)
            }

            override fun onSelectOtherMonth(offset: Int) {
                //偏移量 -1表示刷新成上一个月数据 ， 1表示刷新成下一个月数据
                mainBinding.calendarView.selectOtherMonth(offset)
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainBinding = ActivityMain2Binding.inflate(layoutInflater)
        setContentView(mainBinding.root)

        initCalendarView()
        refreshMonthPager()

        mainBinding.nextMonth.setOnClickListener {
            mainBinding.calendarView.currentItem = mainBinding.calendarView.currentPosition + 1
        }

        mainBinding.preMonth.setOnClickListener {
            mainBinding.calendarView.currentItem = mainBinding.calendarView.currentPosition - 1
        }

        mainBinding.today.setOnClickListener {
            refreshMonthPager()
        }

        mainBinding.btn.setOnClickListener {
//            val markData = HashMap<String, String>()
//            markData["${mainBinding.et.text}"] = "1"
            Utils.loadMarkData()["${mainBinding.et.text}"] = "1"
            calendarAdapter.invalidateCalendar()
//            calendarAdapter.setMarkData(markData)
//            calendarAdapter.invalidateCurrentCalendar()
//            mainBinding.calendarView.currentItem = mainBinding.calendarView.currentPosition
        }
    }

    /**
     * 初始化CustomDayView，并作为CalendarViewAdapter的参数传入
     */
    private fun initCalendarView() {
//        initListener()
        val customDayView = CustomDayView(this, R.layout.custom_day)
        calendarAdapter = CalendarViewAdapter(
            this,
            onSelectDateListener,
            CalendarAttr.WeekArrayType.Monday,
            customDayView
        )
        calendarAdapter.setOnCalendarTypeChangedListener {
            //                rvToDoList.scrollToPosition(0)
        }
        initMarkData()
        initMonthPager()
    }

    /**
     * 初始化标记数据，HashMap的形式，可自定义
     * 如果存在异步的话，在使用setMarkData之后调用 calendarAdapter.notifyDataChanged();
     */
    private fun initMarkData() {
        val markData = HashMap<String, String>()
        markData["2022-2-16"] = "1"
        markData["2022-2-17"] = "1"
        markData["2022-2-1"] = "1"
        markData["2022-2-2"] = "1"
        markData["2022-3-1"] = "1"
        calendarAdapter.setMarkData(markData)
    }

    /**
     * 初始化monthPager，MonthPager继承自ViewPager
     *
     * @return void
     */
    private fun initMonthPager() {
//        Const.minDate = CalendarDate(2022,1,28)
//        Const.maxDate = CalendarDate()
        mainBinding.calendarView.adapter = calendarAdapter
        mainBinding.calendarView.currentItem = MonthPager.CURRENT_DAY_INDEX
        mainBinding.calendarView.setPageTransformer(
            false
        ) { page, position ->
            var position = position
            position = Math.sqrt((1 - Math.abs(position)).toDouble()).toFloat()
            page.alpha = position
        }
        mainBinding.calendarView.addOnPageChangeListener(object : MonthPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {}

            override fun onPageSelected(position: Int) {}

            override fun onPageScrollStateChanged(state: Int) {
                Log.d("TAG", "onPageScrollStateChanged: $state")
                if (0 == state) {
                    val position = mainBinding.calendarView.currentPosition
                    mCurrentPage = position
                    currentCalendars = calendarAdapter.pagers
                    val date: CalendarDate =
                        currentCalendars[position % currentCalendars.size].seedDate
                    mainBinding.date.text = "${date.getYear()}.${getMonth(date.getMonth())}"
                }
            }
        })
    }


    @SuppressLint("SetTextI18n")
    private fun refreshMonthPager(date: CalendarDate) {
        calendarAdapter.notifyDataChanged(date)
        mainBinding.date.text = "${date.getYear()}.${getMonth(date.getMonth())}"
    }

    private fun refreshMonthPager() {
        refreshMonthPager(CalendarDate())
    }

    private fun getMonth(month: Int): String =
        when {
            month < 10 -> {
                "0$month"
            }
            else -> {
                "$month"
            }
        }

    /**
     * onWindowFocusChanged回调时，将当前月的种子日期修改为今天
     *
     * @return void
     */
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus && !initiated) {
            refreshMonthPager()
            initiated = true
        }
    }
}